﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MelodysDemo.API.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    [AllowAnonymous]
    public class LoginController : Controller
    {
        readonly IRepository<SurveyUser, int> _userRepository;//用户
        readonly IConfiguration _configuration;
        public LoginController(IRepository<SurveyUser, int> userRepository,
                               IConfiguration configuration)
        {
            _userRepository = userRepository;
            _configuration = configuration;

        }
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginInput input)
        {
            var u = await _userRepository.FirstOrDefaultAsync(u => u.Phone.Equals(input.Username));
            if (u != null)
            {
                if (u.Status == 1)
                {
                    string uPwd = PwdEncryption.HashPassword(input.Password);//先将密码进行哈希加密
                    if (u.Password.Equals(uPwd))
                    {
                        //验证成功，生成JWT令牌 token
                        //2.生成JWT
                        //Header,选择签名算法
                        var signingAlogorithm = SecurityAlgorithms.HmacSha256;
                        //Payload,存放用户信息，下面我们放了一个用户id
                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub,u.Id.ToString()),
                            new Claim(ClaimTypes.Name,u.Username)
                        };
                        //Signature
                        //取出私钥并以utf8编码字节输出
                        var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
                        //使用非对称算法对私钥进行加密
                        var signingKey = new SymmetricSecurityKey(secretByte);
                        //使用HmacSha256来验证加密后的私钥生成数字签名
                        var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
                        //生成Token
                        var Token = new JwtSecurityToken(
                                issuer: _configuration["Authentication:Issuer"],        //发布者
                                audience: _configuration["Authentication:Audience"],    //接收者
                                claims: claims,                                         //存放的用户信息
                                notBefore: DateTime.UtcNow,                             //发布时间
                                expires: DateTime.UtcNow.AddMinutes(60),           //有效期设置为60分钟
                                signingCredentials                                      //数字签名
                            );
                        //生成字符串token
                        var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
                        return Json(new { code = 0, msg = "登录成功", rmk = TokenStr, uname = u.Username });
                    }
                    return Json(new UIResult(-1, "密码错误"));
                }
                return Json(new UIResult(-1, "用户已禁用，请联系管理员解禁"));
            }
            return Json(new UIResult(-1, "用户不存在"));
        }

        [HttpGet]
        [Authorize]
        public IActionResult test()
        {
            return Ok("test");
        }
    }
}
